# -*- coding: utf-8 -*-


import logging
import sys
import os

sys.path.insert(1, os.path.dirname(os.path.dirname(os.path.abspath(""))))
from common.utils.file_util import get_log_dir


class GenerateLog(object):
    def __init__(self, file):
        self.level = logging.DEBUG
        self.log_file = get_log_dir(file)
        self.loggers = logging.getLogger(file)
        self.formatter = logging.Formatter(
            "%(asctime)s file: %(filename)s line: %(lineno)d - %(levelname)s - %(message)s")

    def console_logger(self):
        """
        将信息打印到控制台
        :return:
        """
        self.loggers.setLevel(level=self.level)
        console = logging.StreamHandler()
        console.setLevel(logging.INFO)
        console.setFormatter(self.formatter)
        self.loggers.addHandler(console)
        return self.loggers

    def file_logger(self):
        '''
        将信息写入到日志文件，如果路径不存在则自动生成
        :return: logger对象
        '''
        self.loggers.setLevel(level=self.level)
        handler = logging.FileHandler(self.log_file, encoding="utf-8")
        handler.setLevel(level=self.level)
        handler.setFormatter(self.formatter)
        self.loggers.addHandler(handler)
        return self.loggers

    def logger(self):
        """
        讲信息输出到控制台且合并写入文件
        :return: logger对象
        """
        self.loggers.setLevel(level=self.level)
        console = logging.StreamHandler()
        console.setLevel(logging.INFO)
        console.setFormatter(self.formatter)

        handler = logging.FileHandler(self.log_file, encoding="utf-8")
        handler.setLevel(level=self.level)
        handler.setFormatter(self.formatter)

        self.loggers.addHandler(console)
        self.loggers.addHandler(handler)
        return self.loggers
